<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <script src="https://cdn.jsdelivr.net/npm/vue@2"></script>
    <!-- 引入样式 -->
    <link href="https://unpkg.com/element-ui/lib/theme-chalk/index.css" rel="stylesheet">
    <!-- 引入组件库 -->
    <script src="https://unpkg.com/element-ui/lib/index.js"></script>
    <script src="../app/lib/ZohoCrmHelper.js" type="text/javascript"></script>
    <script src="../app/lib/ZSDK.js" type="text/javascript"></script>
    <script src="../app/lib/jquery-1.10.2.js" type="text/javascript"></script>
    <script src="../app/lib/ZohoEmbededAppSDK.min.js" type="text/javascript"></script>
    <script src="../app/lib/axios.min.js" type="text/javascript"></script>
    <title>选择入库单号</title>
</head>

<body style="padding: 20px;">
<div id="app">
    <div class="page-header">
        <h2>入库单选择</h2>
        <el-button type="primary" @click="saveData" class="save-btn">保存</el-button>
    </div>

    <el-table
            :data="tableData"
            border
            style="width: 100%; margin-top: 20px;"
            :header-cell-style="{background: '#f5f7fa', color: '#333', fontWeight: 'bold'}">
        <el-table-column
                prop="skuName"
                label="SKU"
                align="center"
                width="180">
        </el-table-column>
        <el-table-column
                prop="receiptNo"
                label="入库单号"
                align="center">
            <template slot-scope="scope">
                <el-select
                        v-model="scope.row.receiptNo"
                        placeholder="请选择或输入入库单号"
                        filterable
                        allow-create
                        default-first-option
                        style="width: 100%;">
                    <!-- 动态获取当前SKU对应的选项 -->
                    <el-option
                            v-for="item in getReceiptOptions(scope.row.skuId)"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value">
                    </el-option>
                </el-select>
            </template>
        </el-table-column>
    </el-table>
</div>
</body>
</html>

<script type="text/javascript">
    const app = new Vue({
        el: '#app',
        data() {
            return {
                crmId: "",
                selectedFiles: [],
                // 表格数据
                tableData: [],
                // 所有入库单号选项（完整集合）
                allReceiptOptions: [
                    {value: 'IN2023001', label: 'IN2023001'},
                    {value: 'IN2023002', label: 'IN2023002'},
                    {value: 'IN2023003', label: 'IN2023003'},
                    {value: 'IN2023004', label: 'IN2023004'},
                    {value: 'IN2023005', label: 'IN2023005'},
                    {value: 'IN2023006', label: 'IN2023006'},
                    {value: 'IN2023007', label: 'IN2023007'},
                    {value: 'IN2023008', label: 'IN2023008'},
                    {value: 'IN2023009', label: 'IN2023009'},
                    {value: 'IN2023010', label: 'IN2023010'}
                ],
                // SKU与入库单号的映射关系（动态数据）
                // 格式：{ sku值: [对应的入库单value数组] }
                skuToReceiptMap: {},
                // 默认选项（当SKU在映射表中无匹配时使用）
                defaultReceipts: ['IN2023001', 'IN2023002', 'IN2023003', 'IN2023004', 'IN2023005']
            };
        },
        mounted() {
            this.initData();
            ZOHO.embeddedApp.init();
        },
        methods: {
            initData() {
                ZOHO.embeddedApp.on("PageLoad", (data) => {
                    this.crmId = data.EntityId;
                    ZOHO.CRM.UI.Resize({height: "100%", width: "100%"}).then(() => {
                        this.getCRMData();
                    });
                });
            },
            getCRMData() {
                // 使用连接器，查询子表单数据
                const req_data = {
                    "parameters": {},
                    "headers": {},
                    "method": "GET",
                    "url": `https://www.zohoapis.com.cn/crm/v7/Accounts/${this.crmId}`,
                    "param_type": 2
                };
                ZOHO.CRM.CONNECTION.invoke("crm", req_data).then(async (data) => {
                    if (!data.code.includes("SUCCESS")) {
                        console.log("查询数据失败=" + JSON.stringify(data));
                        return;
                    }
                    const crmData = data.details.statusMessage.data[0];
                    const linkingModule8 = crmData.LinkingModule8;
                    this.processTableData(linkingModule8);
                }).catch((error) => {
                    console.error("获取记录时出现错误:", error);
                });
            },
            // 处理表格数据
            async processTableData(dataList) {
                if (Array.isArray(dataList)) {
                    this.skuToReceiptMap = {}; // 清空映射表
                    this.tableData = []; // 清空表格数据

                    // 循环处理每条数据，确保异步操作完成
                    for (const item of dataList) {
                        const skuId = item.sku?.id || '';
                        const skuName = item.sku?.name || '';
                        // 获取已有的receiptNo值
                        const existingReceiptNo = item.receiptNo || '';

                        // 等待当前SKU的入库单数据加载完成
                        await this.buildSkuMap(skuId);

                        // 确定默认选中的入库单号
                        let defaultReceipt = '';
                        const skuReceipts = this.skuToReceiptMap[skuId] || [];

                        // 如果已有值且在可选列表中，则优先使用
                        if (existingReceiptNo && (skuReceipts.includes(existingReceiptNo) || this.defaultReceipts.includes(existingReceiptNo))) {
                            defaultReceipt = existingReceiptNo;
                        }
                        // 否则使用列表中的第一个值
                        else if (skuReceipts.length > 0) {
                            defaultReceipt = skuReceipts[0];
                        }

                        // 添加到表格数据
                        this.tableData.push({
                            id: item.id,
                            skuId: skuId,
                            skuName: skuName,
                            receiptNo: defaultReceipt
                        });
                    }
                } else {
                    console.error("获取的子表单数据不是数组");
                    this.tableData = [];
                    this.skuToReceiptMap = {};
                }
            },
            // 构建SKU与入库单的映射关系
            async buildSkuMap(skuId) {
                if (skuId && !this.skuToReceiptMap[skuId]) { // 避免重复查询
                    this.skuToReceiptMap[skuId] = await this.selectData(skuId);
                }
            },
            // 查询SKU对应的入库单数据
            async selectData(id) {
                const array = [];
                const request = {
                    Entity: "Sales_Orders",
                    Type: "criteria",
                    Query: `(account.id:starts_with:${id})`,
                    sort_order: "asc",
                };
                try {
                    const data = await ZOHO.CRM.API.searchRecord(request);
                    if (data.status !== 204 && data.data !== undefined) {
                        data.data.forEach(obj => {
                            if (obj.SO_Number) {
                                array.push(obj.SO_Number);
                            }
                        });
                    }
                } catch (error) {
                    console.error(`查询SKU ${id} 对应的入库单失败:`, error);
                }
                return array;
            },
            // 动态获取当前SKU对应的入库单选项
            getReceiptOptions(skuId) {
                // 从映射表中获取当前SKU对应的入库单数组
                const matchedValues = this.skuToReceiptMap[skuId] || this.defaultReceipts;

                // 构建选项列表（如果映射表中有数据，直接使用；否则用默认选项）
                return matchedValues.map(value => ({
                    value: value,
                    label: value
                }));
            },
            // 保存数据
            saveData() {
                const saveData = this.tableData.map(row => ({
                    id: row.id,
                    receiptNo: row.receiptNo
                }));


                let updateData = {
                    Entity: "Accounts",
                    APIData: {
                        "id": this.crmId + "",
                        "LinkingModule8": saveData
                    },
                    Trigger:["workflow"]
                }
                ZOHO.CRM.API.updateRecord(updateData).then(function (data) {
                    console.log(data);
                    if (data.data[0].code === "SUCCESS") {
                        app.$message({
                            type: 'success',
                            message: '修改成功!'
                        });
                        ZOHO.CRM.UI.Popup.closeReload().then(function (data) {
                            console.log(data);
                        });
                    } else {
                        app.$message({
                            message: data.data[0].message,
                            type: 'error'
                        });
                    }
                });

                console.log('保存的数据:', saveData);
            }
        }
    });
</script>
<style>
    .page-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 15px;
        padding-bottom: 10px;
        border-bottom: 1px solid #eaeaea;
    }

    .page-header h2 {
        margin: 0;
        color: #1f2d3d;
        font-size: 18px;
    }

    .save-btn {
        background-color: #409eff;
        border-color: #409eff;
    }

    .el-table {
        box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
        border-radius: 4px;
        overflow: hidden;
    }

    .el-select {
        width: 100%;
    }
</style>
